import React, { useEffect } from "react";
import { useNavigate } from "react-router-dom";
import { api } from "@/api/api";
import { useDispatch, useSelector, connect } from "react-redux";
import { setShopInfo } from "@/store/actions/shopActions";

const Index = () => {
  const dispatch = useDispatch();
  const navigate = useNavigate();
  const shop = useSelector((state) => state.shop);
  const shopId = localStorage.getItem("shop_id");
  // 初始化VConsole
  useEffect(() => {
    // new window.VConsole();
  }, []);

  const getshopInfo = async () => {
    try {
      const res = await api.getShopInfo({ shopId: shop.shopId || shopId });
      dispatch(setShopInfo(res.data));
    } catch (error) {
      console.log(error);
    }
  };

  const getUserLocation = async () => {
    if ("geolocation" in navigator) {
      navigator.geolocation.getCurrentPosition(
        (position) => {
          console.log(position);
        },
        (error) => {
          console.log(error);
        },
        {
          enableHighAccuracy: true,
          timeout: 5000,
          maximumAge: 0,
        }
      );
    }
  };

  useEffect(() => {
    const initializeApp = async () => {
      // 初始化wx授权配置
      if (window.wx) {
        try {
          const res = await api.getBuildJsSdkSignature({
            shopId: shop.shopId || shopId,
            urls: window.location.href.split('#')[0],
          });
          const config = res.data;
          window.wx.config({
              debug: false,
              appId: config.appid,
              timestamp: config.timestamp,
              nonceStr: config.nonceStr,
              signature: config.signature,
              jsApiList: ['chooseImage']
          });
        } catch (error) {
          console.log(error);
        }
      }
      // 初始化应用数据
      await getshopInfo();
      getUserLocation();

      // 初始化完成后跳转到首页
      navigate("/home", { replace: true });
    };

    initializeApp();
  }, [navigate, dispatch]);

  return (
    <div
      style={{
        display: "flex",
        justifyContent: "center",
        alignItems: "center",
        height: "100vh",
        fontSize: "16px",
      }}
    >
      正在初始化应用...
    </div>
  );
};

export default Index;
